package org.jeecg.modules.demo.com.kunpeng.controller;

import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.com.kunpeng.entity.SupplierManagement;
import org.jeecg.modules.demo.com.kunpeng.entity.dto.SupplierManagementQueryListDTO;
import org.jeecg.modules.demo.com.kunpeng.service.ISupplierManagementService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.demo.com.kunpeng.vo.SupplierManagementQueryListVO;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 供应商管理表
 * @Author: jeecg-boot
 * @Date:   2023-01-09
 * @Version: V1.0
 */
@Api(tags="供应商管理表")
@RestController
@RequestMapping("/com.kunpeng/supplierManagement")
@Slf4j
public class SupplierManagementController extends JeecgController<SupplierManagement, ISupplierManagementService> {
	@Autowired
	private ISupplierManagementService supplierManagementService;

	/**
	 * 分页列表查询
	 *
	 * @param supplierManagement
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "供应商管理表-分页列表查询")
	@ApiOperation(value="供应商管理表-分页列表查询", notes="供应商管理表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<SupplierManagement>> queryPageList(SupplierManagement supplierManagement,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<SupplierManagement> queryWrapper = QueryGenerator.initQueryWrapper(supplierManagement, req.getParameterMap());
		Page<SupplierManagement> page = new Page<SupplierManagement>(pageNo, pageSize);
		IPage<SupplierManagement> pageList = supplierManagementService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param supplierManagement
	 * @return
	 */
	@AutoLog(value = "供应商管理表-添加")
	@ApiOperation(value="供应商管理表-添加", notes="供应商管理表-添加")
	//@RequiresPermissions("com.kunpeng:supplier_management:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody SupplierManagement supplierManagement) {
		supplierManagementService.insert(supplierManagement);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param supplierManagement
	 * @return
	 */
	@AutoLog(value = "供应商管理表-编辑")
	@ApiOperation(value="供应商管理表-编辑", notes="供应商管理表-编辑")
	//@RequiresPermissions("com.kunpeng:supplier_management:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody SupplierManagement supplierManagement) {
		supplierManagementService.updateById(supplierManagement);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "供应商管理表-通过id删除")
	@ApiOperation(value="供应商管理表-通过id删除", notes="供应商管理表-通过id删除")
	//@RequiresPermissions("com.kunpeng:supplier_management:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		supplierManagementService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "供应商管理表-批量删除")
	@ApiOperation(value="供应商管理表-批量删除", notes="供应商管理表-批量删除")
	//@RequiresPermissions("com.kunpeng:supplier_management:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.supplierManagementService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "供应商管理表-通过id查询")
	@ApiOperation(value="供应商管理表-通过id查询", notes="供应商管理表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<SupplierManagement> queryById(@RequestParam(name="id",required=true) String id) {
		SupplierManagement supplierManagement = supplierManagementService.getById(id);
		if(supplierManagement==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(supplierManagement);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param supplierManagement
    */
    //@RequiresPermissions("com.kunpeng:supplier_management:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SupplierManagement supplierManagement) {
        return super.exportXls(request, supplierManagement, SupplierManagement.class, "供应商管理表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("com.kunpeng:supplier_management:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SupplierManagement.class);
    }


	 /**
	  * 供应商管理关键字查询
	  */
	 @ApiOperation(value = "供应商管理表-关键字查询", notes = "供应商管理表-关键字查询")
	 @PostMapping(value = "/supplierManagementQueryList")
	 public Result<IPage<SupplierManagementQueryListVO>> supplierManagementQueryList(@RequestBody SupplierManagementQueryListDTO supplierManagementQueryListDTO,
																				  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
																				  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
		 log.info("开始处理根据关键字查询项目列表请求...");
		 Result<Page<SupplierManagementQueryListVO>> result = new Result<Page<SupplierManagementQueryListVO>>();
		 Page<SupplierManagementQueryListVO> pageList = new Page<SupplierManagementQueryListVO>(pageNo, pageSize);
		 pageList = supplierManagementService.queryListByKeyWords(pageList,supplierManagementQueryListDTO);//通知公告消息
		 if (pageList.getRecords().size() == 0) {
			 return Result.error("没有符合条件的数据，请重新输入！");
		 }
		 log.info("查询当前页：" + pageList.getCurrent());
		 log.info("查询当前页数量：" + pageList.getSize());
		 log.info("查询结果数量：" + pageList.getRecords().size());
		 log.info("数据总数：" + pageList.getTotal());
		 result.setSuccess(true);
		 result.setResult(pageList);
		 return Result.ok(pageList);
	 }

	 /**
	  * 修改isDelete状态
	  */
	 @ApiOperation(value = "供应商管理表-修改isDelete状态",notes = "供应商管理表-修改isDelete状态")
	 @GetMapping(value = "/updateIsDeleteState")
	 public Result<String> updateIsDeleteState(String id ,String isDelete){
		 System.out.println("开始处理根据id修改isDelete状态请求...");
	 	supplierManagementService.updateIsDelete(id,isDelete);
	 	return Result.ok("修改成功");
	 }

	 /**
	  * 处理文件上传
	  * @param pic
	  * @return
	  */
	 @ApiOperation(value = "文件上传接口")
	 @PostMapping(value = "/upload")
	 public Result<String> upload(@RequestPart("file")MultipartFile pic){
		 String fileDir="E:/supplierProofFiles";
		 String fileName=pic.getOriginalFilename();
		 String suffix=fileName.substring(fileName.lastIndexOf("."));
		 fileName= UUID.randomUUID()+suffix;
		 //文件夹不存在则创建
		 File dirFile=new File(fileDir);
		 if(!dirFile.exists()){
			 dirFile.mkdirs();
		 }
		 //文件写入磁盘
		 String filePath=fileDir+"/"+fileName;
		 try {
			 pic.transferTo(new File(filePath));
		 } catch (IOException e) {
			 e.getMessage();
		 }
		 //返回文件的路径
		 return Result.ok(filePath);
	 }


	 /**
	  * 文件下载接口
	  *
	  * @param
	  * @param response
	  * @return
	  */
	 @ApiOperation(value = "文件下载接口")
	 @GetMapping(value = "/download")
	 public void downLoad(String filePath,HttpServletRequest request, HttpServletResponse response) throws Exception {
         System.out.println("***********filePath:"+filePath);
	 	File file=new File(filePath);
	 	response.setCharacterEncoding("utf-8");
	 	InputStream is=null;
	 	OutputStream os=null;
	 	try {
	 		//分片下载
	 		long fSize=file.length();
	 		response.setContentType("application/x-download");
	 		String fileName= URLEncoder.encode(file.getName(),"utf-8");
	 		response.addHeader("Content-Disposition","attachment;filename="+fileName);
	 		response.setHeader("Accept-Range","bytes");

	 		response.setHeader("fSize",String.valueOf(fSize));
			response.setHeader("fName",String.valueOf(fileName));

			long pos=0,last=fSize-1,sum=0;
			if(null!=request.getHeader("Range")){
				response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

				String numRange = request.getHeader("Range").replaceAll("bytes=", "");
				String[] strRange = numRange.split("-");
				if(strRange.length==2){
					pos=Long.parseLong(strRange[0].trim());
					last=Long.parseLong(strRange[1].trim());
					if(last>fSize-1){
						last=fSize-1;
					}
				}else {
					pos=Long.parseLong(numRange.replaceAll("-","").trim());
				}
			}
			long rangeLength=last-pos+1;
			String contentRange=new StringBuffer("bytes").append(pos).append("-").append(last).append("/").append(fSize).toString();
			response.setHeader("Content-Range",contentRange);
			response.setHeader("Content-Length",String.valueOf(rangeLength));

			os=new BufferedOutputStream(response.getOutputStream());
			is=new BufferedInputStream(new FileInputStream(file));
			is.skip(pos);
			byte[] buffer=new byte[1024];
			int length=0;
			while (sum<rangeLength){
				length=is.read(buffer,0,((rangeLength-sum)<= buffer.length ? ((int)(rangeLength-sum)) : buffer.length));
				sum=sum+length;
				os.write(buffer,0,length);
			}
			log.info("下载完成！");
		}finally {
	 		if(is!=null){
	 			is.close();
			}
	 		if(os!=null){
	 			os.close();
			}
		}

		/* File f = new File(filePath);
		 if (!f.exists()) {
			 response.sendError(404, "File not found!");
			 return;
		 }
		 BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
		 byte[] buf = new byte[1024];
		 int len = 0;

		 response.reset(); // 非常重要
		 *//*if (isOnLine) { // 在线打开方式
			 URL u = new URL("file:///" + filePath);
			 response.setContentType(u.openConnection().getContentType());
			 response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
			 // 文件名应该编码成UTF-8
		 } else { // 纯下载方式
			 response.setContentType("application/x-msdownload");
			 response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
		 }*//*
		 response.setContentType("application/x-msdownload");
		 response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
		 OutputStream out = response.getOutputStream();
		 while ((len = br.read(buf)) > 0)
			 out.write(buf, 0, len);
		 br.close();
		 out.close();*/
	 }
	 /*public Object download(@RequestParam String path, HttpServletResponse response) throws IOException {

		 //获取文件hash一样的文件（hash相同代表是同一个文件）
		 *//*List<TestFile > testFileHS = testFileMapper.selectList(new QueryWrapper<TestFile>()
						 .eq("file_hash",testFile.getFileHash())*//*
				 // 获取testFileHS中的第一个对象并塞进file中
		 log.info("path:"+path);
		 File file = new File(path);
		 if (!file.exists()) {
			 log.info("当前附件本地文件不存在！");
		 }
		 //设置请求头
		 response.setHeader("Content-Disposition", "attachment;filename=a.jpg");
		 //设置类型
		 response.setContentType("application/x-msdownload");
		 //设置编码
		 response.setCharacterEncoding("utf-8");
		 FileInputStream bis;
		 OutputStream os;
		 try {
			 //将file对象塞进一个输入流中
			 bis = new FileInputStream(file);
			 //创建一个byte对象
			 byte[] buff = new byte[1024];
			 //获取输出流
			 os = response.getOutputStream();
			 int i = 0;
			 //当file对象的输入流没有结束的时候，通过输出流写出
			 while ((i = bis.read(buff)) != -1) {
				 os.write(buff, 0, i);
			 }
			 bis.close();
			 os.close();

		 } catch (IOException e) {
			 log.info("下载失败！");
		 }
		 return file;
	 }*/


		/* try {
			 // path是指预下载的文件的路径。
			 File file = new File(path);
			 // 取得文件名。
			 String filename = file.getName();
			 // 取得文件的后缀名。
			 String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
			 // 以流的形式下载文件。
			 InputStream fis = new BufferedInputStream(new FileInputStream(path));
			 byte[] buffer = new byte[fis.available()];
			 fis.read(buffer);
			 fis.close();
			 // 清空response
			 response.reset();
			 // 设置response的Header
			 response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
			 response.addHeader("Content-Length", "" + file.length());
			 OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			 response.setContentType("application/octet-stream");
			 response.reset();
			 toClient.write(buffer);
			 toClient.flush();
			 toClient.close();
		 } catch (IOException ex) {
			 ex.printStackTrace();
		 }
		 return Result.ok(response);
	 }*/
 }